#include "ParamGroupLimitsView.h"
#include "ui_ParamGroupLimitsForm.h"
#include "GlobalApi/sqlitedb.h"
#include "Auxiliary/View/MessageBoxDialog.h"
#include <QListView>
#include <QSqlRecord>
#include <QDebug>


ParamGroupLimitsView::ParamGroupLimitsView(bool isNewGroup, int selectGroup, QSqlTableModel *model, QWidget *parent):
    QWidget(parent), pModel(model),
        m_selectGroup(selectGroup),
        m_isNewGroup(isNewGroup),
        ui(new Ui::ParamGroupLimits)
{
   ui->setupUi(this);
   this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);//隐藏标题设置为顶层显示
   tc = QTextCodec::codecForName("UTF-8");
   paramGroupDao = new ParamGroupDao();
   readParamGroupInfo(paramGroupDao); //从数据库中获取参考组数据
   initUi();

}

ParamGroupLimitsView::~ParamGroupLimitsView()
{
    delete ui;
    delete paramGroupDao;
}

void ParamGroupLimitsView::initUi()
{
    initTable();  //创建控件表格

    ui->ch_lineEdit_groupName->setText(paramGroupDao->groupName);

    ui->nu_lineEdit_ageLow->setText(paramGroupDao->ageLowerLimit);  //设定年龄下限及单位
    int index = ui->comboBox_ageLow->findText(paramGroupDao->ageLowerType);
    if(index == -1){
       ui->comboBox_ageLow->setCurrentIndex(0);
    } else {
       ui->comboBox_ageLow->setCurrentIndex(index);
    }

    ui->nu_lineEdit_ageUp->setText(paramGroupDao->ageUpperLimit);  //设定年龄上限及单位
    index = ui->comboBox_ageUp->findText(paramGroupDao->ageUpperType);
    if(index == -1){
        ui->comboBox_ageUp->setCurrentIndex(0);
    } else{
        ui->comboBox_ageUp->setCurrentIndex(index);
    }

    index = ui->comboBox_sex->findText(paramGroupDao->sex);   //设定性别
    if(index == -1) {
        ui->comboBox_sex->setCurrentIndex(0);
    } else {
        ui->comboBox_sex->setCurrentIndex(index);
    }

    //填充参数下限（左侧表格有15个参数，右侧有14个参数）
    for(int i = 1; i < 16; i++)
    {
        ui->tableWidget_groupLimits1->item(i, 1)->setText(paramGroupDao->valueLower[i-1]);  //表格1下限值
        ui->tableWidget_groupLimits1->item(i, 2)->setText(paramGroupDao->valueUpper[i-1]);  //表格1上限值
    }
    for(int i = 1; i < 15; i++)
    {
        ui->tableWidget_groupLimits2->item(i, 1)->setText(paramGroupDao->valueLower[15+i-1]);  //表格2下限值
        ui->tableWidget_groupLimits2->item(i, 2)->setText(paramGroupDao->valueUpper[15+i-1]);  //表格2上限值
    }
}

void ParamGroupLimitsView::initTable()
{
    int i=0,j=0;
    QString groupTile[3]={tr("参数"), tr("下限"), tr("上限")};
    const char *groupItem[30]={"WBC","Neu#","Lym#","Mon#","Eos#","Bas#","Neu%","Lym%","Mon%","Eos%","Bas%","*ALY#","*ALY%","*LIC#","*LIC%", \
                               "RBC","HGB","HCT","MCV","MCH","MCHC","RDW-CV","RDW-SD","PLT","MPV","PDW","PCT","P-LCC","P-LCR",""};

    ui->tableWidget_groupLimits1->setColumnCount(3);
    ui->tableWidget_groupLimits1->setRowCount(20);
    ui->tableWidget_groupLimits1->setEditTriggers(QAbstractItemView::AllEditTriggers );//编辑
    ui->tableWidget_groupLimits1->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->tableWidget_groupLimits1->verticalHeader()->setResizeMode(QHeaderView::Fixed);
    ui->tableWidget_groupLimits1->setSelectionMode(QAbstractItemView::NoSelection); //选择
   // ui->tableWidget_groupLimits1->setSelectionMode(QAbstractItemView::SingleSelection); //选择
   // ui->tableWidget_groupLimits1->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->tableWidget_groupLimits1->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    ui->tableWidget_groupLimits1->verticalHeader()->hide();
    ui->tableWidget_groupLimits1->horizontalHeader()->hide();


    ui->tableWidget_groupLimits2->setColumnCount(3);
    ui->tableWidget_groupLimits2->setRowCount(18);
    ui->tableWidget_groupLimits2->setEditTriggers(QAbstractItemView::AllEditTriggers );//编辑
    ui->tableWidget_groupLimits2->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
    ui->tableWidget_groupLimits2->verticalHeader()->setResizeMode(QHeaderView::Fixed);
    ui->tableWidget_groupLimits2->setSelectionMode(QAbstractItemView::NoSelection); //选择
    //ui->tableWidget_groupLimits2->setSelectionMode(QAbstractItemView::SingleSelection); //选择
    //ui->tableWidget_groupLimits2->setSelectionBehavior(QAbstractItemView::SelectItems);
    ui->tableWidget_groupLimits2->verticalHeader()->setDefaultAlignment(Qt::AlignCenter);
    ui->tableWidget_groupLimits2->verticalHeader()->hide();
    ui->tableWidget_groupLimits2->horizontalHeader()->hide();


    // 设置表名
    for(i = 0;i<3;++i)
    {
        ui->tableWidget_groupLimits1->setItem(0,i,new QTableWidgetItem(groupTile[i]));
       // ui->tableWidget_groupLimits1->item(0,i)->setFlags( Qt::ItemIsSelectable );
        ui->tableWidget_groupLimits1->item(0,i)->setFlags(ui->tableWidget_groupLimits1->item(0,i)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits1->item(0,i)->setTextColor( QColor(0, 0, 0) );
      //ui->tableWidget_groupLimits1->item(0,i)->setFont( QFont( "Times", 8, QFont::Normal ) );  //将字体加粗
        ui->tableWidget_groupLimits1->item(0,i)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->item(0,i)->setBackgroundColor(QColor(QColor(102, 204, 153)));
        ui->tableWidget_groupLimits1->item(0,i)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits1->item(0,i)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits2->setItem(0,i,new QTableWidgetItem(groupTile[i]));
      // ui->tableWidget_groupLimits2->item(0,i)->setFlags( Qt::ItemIsSelectable );
        ui->tableWidget_groupLimits2->item(0,i)->setFlags(ui->tableWidget_groupLimits2->item(0,i)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits2->item(0,i)->setTextColor( QColor(0, 0, 0) );
      //ui->tableWidget_groupLimits2->item(0,i)->setFont( QFont( "Times", 8, QFont::Normal ) );  //将字体加粗
        ui->tableWidget_groupLimits2->item(0,i)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->item(0,i)->setBackgroundColor(QColor(QColor(102, 204, 153)));
        ui->tableWidget_groupLimits2->item(0,i)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits2->item(0,i)->setFlags(Qt::NoItemFlags);
    }


    for(i = 1;i<16;++i)
    {

        ui->tableWidget_groupLimits1->setItem(i,0, new QTableWidgetItem(tc->toUnicode(groupItem[i-1])));
        //ui->tableWidget_groupLimits1->item(i,0)->setFlags( Qt::ItemIsSelectable );
        ui->tableWidget_groupLimits1->item(i,0)->setFlags(ui->tableWidget_groupLimits1->item(i,0)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits1->item(i,0)->setTextColor( QColor(0, 0, 0) );
      //ui->tableWidget_groupLimits1->item(i,0)->setFont( QFont( "Helvetica", 8, QFont::Normal ) );  //将字体加粗
        ui->tableWidget_groupLimits1->item(i,0)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->item(i,0)->setBackgroundColor(QColor(102, 204, 153));
        ui->tableWidget_groupLimits1->item(i,0)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits1->item(i,0)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits2->setItem(i,0, new QTableWidgetItem(tc->toUnicode(groupItem[i+14])));
       // ui->tableWidget_groupLimits2->item(i,0)->setFlags( Qt::ItemIsSelectable );
        ui->tableWidget_groupLimits2->item(i,0)->setFlags(ui->tableWidget_groupLimits2->item(i,0)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits2->item(i,0)->setTextColor( QColor(0, 0, 0) );
      //ui->tableWidget_groupLimits2->item(i,0)->setFont( QFont( "Helvetica", 8, QFont::Normal ) );  //将字体加粗
        ui->tableWidget_groupLimits2->item(i,0)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->item(i,0)->setBackgroundColor(QColor(102, 204, 153));
        ui->tableWidget_groupLimits2->item(i,0)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits2->item(i,0)->setFlags(Qt::NoItemFlags);


        ui->tableWidget_groupLimits1->setItem(i,1, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits1->item(i,1)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->setItem(i,2, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits1->item(i,2)->setTextAlignment(Qt::AlignCenter);

        ui->tableWidget_groupLimits2->setItem(i,1, new QTableWidgetItem( "" ) );
        ui->tableWidget_groupLimits2->item(i,1)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->setItem(i,2, new QTableWidgetItem( "" ) );
        ui->tableWidget_groupLimits2->item(i,2)->setTextAlignment(Qt::AlignCenter);

    }

    ui->tableWidget_groupLimits2->item(15,1)->setFlags( Qt::NoItemFlags );
    ui->tableWidget_groupLimits2->item(15,2)->setFlags( Qt::NoItemFlags );

    for(i = 0;i<4;++i)
    {
        ui->tableWidget_groupLimits1->setItem(i+16,0, new QTableWidgetItem(""));
        ui->tableWidget_groupLimits1->item(i+16,0)->setFlags(ui->tableWidget_groupLimits1->item(i,0)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits1->item(i+16,0)->setTextColor( QColor(0, 0, 0) );
        ui->tableWidget_groupLimits1->item(i+16,0)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->item(i+16,0)->setBackgroundColor(QColor(102, 204, 153));
        ui->tableWidget_groupLimits1->item(i+16,0)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits1->item(i+16,0)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits1->setItem(i+16,1, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits1->item(i+16,1)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->item(i+16,1)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits1->setItem(i+16,2, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits1->item(i+16,2)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits1->item(i+16,2)->setFlags(Qt::NoItemFlags);
    }

    for(i = 0;i<2;++i)
    {
        ui->tableWidget_groupLimits2->setItem(i+16,0, new QTableWidgetItem(""));
        ui->tableWidget_groupLimits2->item(i+16,0)->setFlags(ui->tableWidget_groupLimits2->item(i,0)->flags()& (~Qt::ItemIsEditable) );
        ui->tableWidget_groupLimits2->item(i+16,0)->setTextColor( QColor(0, 0, 0) );
        ui->tableWidget_groupLimits2->item(i+16,0)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->item(i+16,0)->setBackgroundColor(QColor(102, 204, 153));
        ui->tableWidget_groupLimits2->item(i+16,0)->setTextColor(QColor(0, 0, 0));
        ui->tableWidget_groupLimits2->item(i+16,0)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits2->setItem(i+16,1, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits2->item(i+16,1)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->item(i+16,1)->setFlags(Qt::NoItemFlags);

        ui->tableWidget_groupLimits2->setItem(i+16,2, new QTableWidgetItem( "" ));
        ui->tableWidget_groupLimits2->item(i+16,2)->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget_groupLimits2->item(i+16,2)->setFlags(Qt::NoItemFlags);
    }

    for(int i=0;i<4;i++)
    {
        ui->tableWidget_groupLimits1->hideRow(16+i);
    }

    for(int i=0;i<2;i++)
    {
        ui->tableWidget_groupLimits2->hideRow(16+i);
    }

    QString stylesheettableWidget_listing = "QTableWidget{background-color:#e2f7eb;"
                                            "alternate-background-color: #ffffff;"
                                            "color: rgb(0, 0, 0);"
                                            "border:1px solid#C9C9C9;"
                                            "selection-color: rgb(255, 255, 255);"
                                            "selection-background-color: rgb(32, 131, 95);}";

    ui->tableWidget_groupLimits1->setAlternatingRowColors(true);//间隔显示颜色
    ui->tableWidget_groupLimits1->setStyleSheet(stylesheettableWidget_listing);
    ui->tableWidget_groupLimits2->setAlternatingRowColors(true);//间隔显示颜色
    ui->tableWidget_groupLimits2->setStyleSheet(stylesheettableWidget_listing);

    //get_groupLimits_from_table();





    if(m_isNewGroup == true)
    {
//        QStringList ageUnit;
//        ageUnit.append(tr("岁"));
//        ageUnit.append(tr("月"));
//        ageUnit.append(tr("天"));
//        ageUnit.append(tr("小时"));
//        ui->comboBox_ageLow->setView(new QListView);
//        ui->comboBox_ageUp->setView(new QListView);
//        ui->comboBox_ageLow->addItems(ageUnit);
//        ui->comboBox_ageUp->addItems(ageUnit);

//        QStringList sexUnit;
//        sexUnit.append(tr("男"));
//        sexUnit.append(tr("女"));
//        sexUnit.append(" ");
//        ui->comboBox_sex->setView(new QListView);
//        ui->comboBox_sex->addItems( sexUnit );

//        QRegExp regx("^\\d{3}$");
//        QValidator *validator1 = new QRegExpValidator(regx, ui->nu_lineEdit_ageLow );
//        QValidator *validator2 = new QRegExpValidator(regx, ui->nu_lineEdit_ageUp );
//        ui->nu_lineEdit_ageLow->setValidator( validator1 );
//        ui->nu_lineEdit_ageUp->setValidator( validator2 );

//        regx.setPattern("^.{1,20}$");
//        QValidator *validator3 = new QRegExpValidator(regx, ui->ch_lineEdit_groupName );
//        ui->ch_lineEdit_groupName->setValidator( validator3 );

    //    for(int i=0 ;i<29;i++)
    //        delegate[i] = new TableViewDelegate(this);

       // get_unitsNation_from_db(1);

        //ui->Btn_save->setStyleSheet(stylesheet_allbutton);
       // ui->Btn_default->setStyleSheet(stylesheet_allbutton);
    }
    else
    {
        readParamGroupInfo(paramGroupDao);  // 初始化

    }
}

void ParamGroupLimitsView::closeEvent(QCloseEvent *event)
{

}

void ParamGroupLimitsView::readParamGroupInfo(ParamGroupDao *dao)
{

    QStringList lowerName,upperName;

    lowerName<<"wbcd"<<"neu1d"<<"lym1d"<<"mon1d"<<"eos1d"<<"bas1d"<<"neu2d" \
             <<"lym2d"<<"mon2d"<<"eos2d"<<"bas2d"<<"aly1d"<<"aly2d"<<"lic1d" \
             <<"lic2d"<<"rbcd"<<"hgbd"<<"hctd"<<"mcvd"<<"mchd"<<"mchcd" \
             <<"rdwcvd"<<"rdwsdd"<<"pltd"<<"mpvd"<<"pdwd"<<"pctd"<<"plccd"<<"plcrd";

    upperName<<"wbcu"<<"neu1u"<<"lym1u"<<"mon1u" <<"eos1u" <<"bas1u" <<"neu2u"  \
              <<"lym2u"<< "mon2u"<<"eos2u"<<"bas2u"<<"aly1u"<<"aly2u"<<"lic1u" \
              <<"lic2u"<<"rbcu"<<"hgbu"<<"hctu"<<"mcvu"<<"mchu"<<"mchcu" \
              <<"rdwcvu"<<"rdwsdu"<<"pltu"<<"mpvu"<<"pdwu"<<"pctu"<<"plccu"<<"plcru";

   // 读取上下限名称
   for(int i = 0; i < 29; i++)
   {
       dao->nameLower[i] = lowerName.at(i);
       dao->nameUpper[i] = upperName.at(i);
   }

    if(m_isNewGroup == true)  // 新建参考组
    {

    }
    else
    {
        if(m_selectGroup < 0 || m_selectGroup > 11)
        {
            qDebug()<<"error selectRow not exists!";
            return;
        }

        QSqlRecord record  = pModel->record(m_selectGroup);
        dao->groupName = record.value("paramGroupName").toString();
        dao->ageLowerLimit = record.value("ageLowerLimit").toString();
        dao->ageLowerType = record.value("ageLowerLimitType").toString();
        dao->ageUpperLimit = record.value("ageUpperLimit").toString();
        dao->ageUpperType = record.value("ageUpperLimitType").toString();
        dao->sex = record.value("sex").toString();

        for(int i = 0; i < 29; i++)
        {
            dao->valueLower[i] = record.value(dao->nameLower[i]).toString();  // 从数据库中获取下限值
            dao->valueUpper[i] = record.value(dao->nameUpper[i]).toString();  // 从数据库中获取上限值
        }
    }
}

void ParamGroupLimitsView::setParamGroupInfo()
{
    paramGroupDao->groupName = ui->ch_lineEdit_groupName->text();
    paramGroupDao->ageLowerLimit = ui->nu_lineEdit_ageLow->text();
    paramGroupDao->ageLowerType = ui->comboBox_ageLow->currentText();
    paramGroupDao->ageUpperLimit = ui->nu_lineEdit_ageUp->text();
    paramGroupDao->ageUpperType = ui->comboBox_ageUp->currentText();
    paramGroupDao->sex = ui->comboBox_sex->currentText();

    // 左侧表格1有15参数，右侧2有14个参数
    for(int i = 1; i < 16; i++)
    {
        paramGroupDao->valueLower[i-1] = ui->tableWidget_groupLimits1->item(i, 1)->text();     // 表格1下限值
        paramGroupDao->valueUpper[i-1] = ui->tableWidget_groupLimits1->item(i, 2)->text();     // 表格1上限值
    }
    for(int i = 1; i < 15; i++)
    {
        paramGroupDao->valueLower[15+i-1] = ui->tableWidget_groupLimits2->item(i, 1)->text();  // 表格2下限值
        paramGroupDao->valueUpper[15+i-1] = ui->tableWidget_groupLimits2->item(i, 2)->text();  // 表格2上限值
    }
}


void ParamGroupLimitsView::on_Btn_default_clicked()
{

}

void ParamGroupLimitsView::on_Btn_save_clicked()
{
    setParamGroupInfo(); // 更新参数信息

    int recordRow;
    if(m_isNewGroup == true)
    {
       int rowNum =  pModel->rowCount();
       pModel->insertRow(rowNum);   // 在数据库中插入新行
       recordRow = rowNum;
    }
    else
    {

       recordRow = m_selectGroup;
    }

    QSqlRecord record;
    record = pModel->record(recordRow);  // 获取需要改写的记录

    if(m_isNewGroup == true)
    {
      record.setValue("ID",  pModel->rowCount());
    }

    record.setValue("paramGroupName", paramGroupDao->groupName);
    record.setValue("ageLowerLimit", paramGroupDao->ageLowerLimit);
    record.setValue("ageLowerLimitType", paramGroupDao->ageLowerType);
    record.setValue("ageUpperLimit", paramGroupDao->ageUpperLimit);
    record.setValue("ageUpperLimitType", paramGroupDao->ageUpperType);
    record.setValue("sex", paramGroupDao->sex);

    // 写入参数上下限值
    for(int i = 0; i < 29; i++)
    {
       record.setValue(paramGroupDao->nameLower[i], paramGroupDao->valueLower[i]);
       record.setValue(paramGroupDao->nameUpper[i], paramGroupDao->valueUpper[i]);
    }

    pModel->setRecord(recordRow, record);

    pModel->database().transaction();  //开始事务操作
    if(pModel->submitAll()){
        pModel->database().commit();   //提交
        qDebug()<<"commit";
    } else {
        pModel->database().rollback();  //回滚
        qDebug()<<"roll back";
    }

    int selectRow;
    if(m_isNewGroup == true)
    {
       selectRow = pModel->rowCount();
    }
    else
    {
       selectRow = m_selectGroup+1;
    }


    emit updateParamReferView(selectRow);

    this->close();
}
